import React, { useCallback } from 'react';
import { StyleSheet, ViewStyle, LayoutAnimation, Platform, UIManager, TouchableOpacity, StyleProp, TextStyle } from 'react-native';
import Animated, { 
  useAnimatedStyle, 
  withTiming, 
  useSharedValue,
} from 'react-native-reanimated';
import { MaterialIcons } from '@expo/vector-icons';
import { ThemedView } from './ThemedView';
import { ThemedText } from './ThemedText';
import { useTheme } from './theme/ThemeContext';

// 在 Android 上启用 LayoutAnimation
if (Platform.OS === 'android') {
  if (UIManager.setLayoutAnimationEnabledExperimental) {
    UIManager.setLayoutAnimationEnabledExperimental(true);
  }
}

interface CollapsibleProps {
  title: string;
  children: React.ReactNode;
  initialExpanded?: boolean;
  style?: StyleProp<ViewStyle>;
}

export function Collapsible({ 
  title, 
  children, 
  initialExpanded = false,
  style 
}: CollapsibleProps) {
  const { theme } = useTheme();
  const [isExpanded, setIsExpanded] = React.useState(initialExpanded);
  const rotateValue = useSharedValue(initialExpanded ? 180 : 0);

  const toggleExpand = useCallback(() => {
    LayoutAnimation.configureNext(LayoutAnimation.Presets.easeInEaseOut);
    setIsExpanded(!isExpanded);
    rotateValue.value = withTiming(isExpanded ? 0 : 180, {
      duration: 300,
    });
  }, [isExpanded, rotateValue]);

  const arrowStyle = useAnimatedStyle(() => {
    return {
      transform: [{ rotate: `${rotateValue.value}deg` }],
    };
  });

  const containerStyle = React.useMemo(() => {
    return StyleSheet.compose(styles.container, style || {});
  }, [style]);

  return (
    <ThemedView
      variant="card"
      style={containerStyle}
    >
      <TouchableOpacity
        style={styles.header}
        onPress={toggleExpand}
        activeOpacity={0.7}
      >
        <ThemedText variant="subtitle" style={styles.title}>
          {title}
        </ThemedText>
        <Animated.View style={arrowStyle}>
          <MaterialIcons
            name="keyboard-arrow-down"
            size={24}
            color={theme.colors.primary}
          />
        </Animated.View>
      </TouchableOpacity>
      {isExpanded && (
        <ThemedView style={styles.content}>
          {children}
        </ThemedView>
      )}
    </ThemedView>
  );
}

const styles = StyleSheet.create({
  container: {
    overflow: 'hidden',
    borderRadius: 8,
    marginVertical: 8,
  } as ViewStyle,
  header: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    padding: 16,
  } as ViewStyle,
  title: {
    flex: 1,
    userSelect: 'none',
  } as TextStyle,
  content: {
    padding: 16,
    paddingTop: 0,
  } as ViewStyle,
});
